package live.zs;

import io.smallrye.common.annotation.Blocking;
import io.smallrye.graphql.client.GraphQLClient;
import io.smallrye.graphql.client.Response;
import io.smallrye.graphql.client.core.Document;
import io.smallrye.graphql.client.core.Field;
import io.smallrye.graphql.client.core.Operation;
import io.smallrye.graphql.client.dynamic.api.DynamicGraphQLClient;
import live.zs.model.Film;
import live.zs.model.FilmConnection;

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;

/**
 * @author madison
 * @description
 * @date 2022/2/5 12:03
 */
/*
    Shows the usage of the typesafe and dynamic GraphQL clients.
    In both cases, the same query is executed against the Star Wars API.
    The query retrieves a list of all films, and for each film, the names of
    all planets which appear in that film.
    The query is:

    {
      allFilms {
        films {
          title
          planetConnection {
            planets {
              name
            }
          }
        }
      }
    }

    You can try executing this query manually on https://graphql.org/swapi-graphql
 */
@Path("/")
public class StarWarsResource {
    // example of typesafe client usage follows

    @Inject
    StarWarsClientApi typesafeClient;

    @GET
    @Path("/typesafe")
    @Produces(MediaType.APPLICATION_JSON)
    @Blocking
    public List<Film> getAllFilmsUsingTypesafeClient() {
        return typesafeClient.allFilms().getFilms();
    }

    // example of dynamic client usage follows

    @Inject
    @GraphQLClient("star-wars-dynamic")
    DynamicGraphQLClient dynamicClient;

    @GET
    @Path("/dynamic")
    @Produces(MediaType.APPLICATION_JSON)
    @Blocking
    public List<Film> getAllFilmsUsingDynamicClient() throws Exception {
        Document query = Document.document(Operation.operation(Field.field("allFilms",
                Field.field("films",
                        Field.field("title"),
                        Field.field("planetConnection",
                                Field.field("planets",
                                        Field.field("name")
                                )))))
        );
        Response response = dynamicClient.executeSync(query);
        return response.getObject(FilmConnection.class, "allFilms").getFilms();
    }
}
